package com.supcon.tea.work.questionnaire.dao;

import com.supcon.tea.work.questionnaire.domain.*;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by zhengjian1 on 2017/7/24.
 */
@Component
@Mapper
public interface QuestionnaireDao {
    @Select("select id,questionnaire_name questionnaireName,questionnaire_type questionnaireType from questionnaire")
    List<Questionnaire> getQuestionnaire();

    @Select("select question_id from questionnaire_question where questionnaire_id = #{id}")
    List<Integer> getQuestionIds(@Param("id") Integer id);

    @SelectProvider(type = MySqlBuilder.class, method = "queryQuestionBySex")
    Question getQuestionBySex(@Param("id") Integer id,@Param("sex") String sex);

    @Select("select id,title,sex,physique_type physiqueType from question")
    List<Question> getQuestion();

    @Select("select `key`,`value`,`score` from `option` where `question_id` = #{id}")
    List<Option> getOptions(@Param("id") Integer id);

    @Select("select max(exist_num) from user_physique where user_id = #{userId} and questionnaire_id = #{questionnaireId}")
    Integer isPhysique(@Param("userId")String userId, @Param("questionnaireId")Integer questionnaireId);

    @Insert("insert into user_physique (user_id,questionnaire_id,rate,physique_type,exist_num,gmt_create) value (#{userId},#{questionnaireId},#{rate},#{physiqueType},#{existNum},now())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    Integer postPhysique(UserPhysique userPhysique);

    @Insert("insert into answer (option_key,question_id,user_physique_id) value (#{optionKey},#{questionId},#{userPhysiqueId})")
    Integer postAnswer(Answer answer);

    @Select("select `id`,`name`,`type`,`mean`,`perplex`,`why`,`careful`,`how`,`recommend` from `physique`")
    List<Physique> getAllPhysique();

    class MySqlBuilder {
        public String queryQuestionBySex(@Param("id") final Integer id,@Param("sex") final Integer sex) {
            StringBuffer sql = new StringBuffer();
            sql.append("select id,title from question where 1=1");
            if(id!= null){
                sql.append(" and id = ").append(id).append(" and (sex = 0");
            }
            if(sex!= -1){
                sql.append(" or sex = ").append(sex).append(")");
            }else{
                sql.append(")");
            }
            return sql.toString();
        }
    }
}
